package com.chuantou.yuba.ui.fragment;

import java.io.File;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.request.MultiPartRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.OtherUserDataTO;
import com.chuantou.yuba.api.to.OtherUserTO;
import com.chuantou.yuba.api.to.UpdateAvatarDataTO;
import com.chuantou.yuba.api.to.UpdateCoverDataTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.ContributionActivity;
import com.chuantou.yuba.ui.FeedbackActivity;
import com.chuantou.yuba.ui.FriendsActivity;
import com.chuantou.yuba.ui.IntegralListActivity;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.ui.MyFavoriteActivity;
import com.chuantou.yuba.ui.MyFishingActivity;
import com.chuantou.yuba.ui.ProfileDetailActivity;
import com.chuantou.yuba.ui.SettingActivity;
import com.chuantou.yuba.ui.TrendsListActivity;
import com.chuantou.yuba.ui.WebViewActivity;
import com.chuantou.yuba.ui.widget.AvatarPickerPopup;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;

/**
 * 个人资料fragment
 * 
 * @author dl1001
 * 
 */
public class ProfileFragment extends BaseFragment implements OnClickListener {
	private View mContentView;
	private TextView mNicknameView;
	private NetworkImageView mAvatarView;
	private NetworkImageView mCoverView;
	private UserTO mUser;
	private AccountManager mAccountManager;
	private AvatarPickerPopup mPopup;
	private ProgressDialog mProgressDialog;
	private boolean mEditAvatar = true;
	private TextView mTrendsCountView;
	private TextView mFollowCountView;
	private TextView mFansCountView;
	private TextView mSexView;
	private TextView mIntegralCountView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAccountManager = AccountManager.getInstance(mContext);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (mContentView == null) {
			mContentView = inflater.inflate(R.layout.fg_profile, null);
			mUser = mAccountManager.getUserTO();
			if (mUser == null) {
				return null;
			}
			setupViews();
			BitmapBinder.bindNetImage(mContext, mCoverView, mUser.getCover(), R.drawable.default_cover, false);
		}
		ViewGroup parentView = (ViewGroup) mContentView.getParent();
		if (parentView != null) {
			parentView.removeView(mContentView);
		}
		return mContentView;
	}

	private void setupViews() {
		mProgressDialog = new ProgressDialog(getActivity());
		mProgressDialog.setMessage(getString(R.string.uploading));
		mProgressDialog.setCancelable(false);
		mContentView.findViewById(R.id.edit).setOnClickListener(this);
		mNicknameView = (TextView) mContentView.findViewById(R.id.nickname);
		mAvatarView = (NetworkImageView) mContentView.findViewById(R.id.avatar);
		mAvatarView.setOnClickListener(this);
		mCoverView = (NetworkImageView) mContentView.findViewById(R.id.cover);
		mCoverView.setOnClickListener(this);
		mContentView.findViewById(R.id.trends_layout).setOnClickListener(this);
		mContentView.findViewById(R.id.my_fishing_date).setOnClickListener(this);
		mContentView.findViewById(R.id.follow_layout).setOnClickListener(this);
		mContentView.findViewById(R.id.fans_layout).setOnClickListener(this);
		mContentView.findViewById(R.id.my_fav).setOnClickListener(this);
		mContentView.findViewById(R.id.feedback).setOnClickListener(this);
		mContentView.findViewById(R.id.about).setOnClickListener(this);
		mContentView.findViewById(R.id.grade).setOnClickListener(this);
		mContentView.findViewById(R.id.more).setOnClickListener(this);
		mContentView.findViewById(R.id.integral).setOnClickListener(this);
		mContentView.findViewById(R.id.contribution).setOnClickListener(this);
		mTrendsCountView = (TextView) mContentView.findViewById(R.id.trends_count);
		mFollowCountView = (TextView) mContentView.findViewById(R.id.follow_count);
		mFansCountView = (TextView) mContentView.findViewById(R.id.fans_count);
		mSexView = (TextView) mContentView.findViewById(R.id.sex);
		mIntegralCountView = (TextView) mContentView.findViewById(R.id.integral_count);
	}

	@Override
	public void onResume() {
		super.onResume();
		mUser = mAccountManager.getUserTO();
		mNicknameView.setText(mUser.getUsername());
		int sex = mUser.getSex();
		if (sex == Constants.SEX_FEMALE) {
			mSexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_female, 0, 0, 0);
			mSexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_female));
		} else {
			mSexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_male, 0, 0, 0);
			mSexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_male));
		}
		BitmapBinder.bindCircularNetImage(mContext, mAvatarView, mUser.getAvatar(), R.drawable.default_avatar_round_small);
		requestProfile();
	}

	private void requestProfile() {
		String url = UriHelper.getUserProfileUrl();
		final UserTO user = mAccountManager.getUserTO();
		mTrendsCountView.setText(String.valueOf(user.getTrendsCount()));
		mFansCountView.setText(String.valueOf(user.getFansCount()));
		mFollowCountView.setText(String.valueOf(user.getFollowCount()));
		mIntegralCountView.setText(String.valueOf(user.getIntegral()));
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		params.put(UriHelper.PARAMS_PROF_UID, String.valueOf(user.getUid()));
		GsonRequest<OtherUserDataTO> request = new GsonRequest<OtherUserDataTO>(Method.POST, url, new Listener<OtherUserDataTO>() {

			@Override
			public void onResponse(OtherUserDataTO response) {
				if (response != null) {
					OtherUserTO profileUser = response.getUser();
					if (profileUser != null) {
						user.setIntegral(profileUser.getIntegral());
						user.setFansCount(profileUser.getFansCount());
						user.setFollowCount(profileUser.getFollowCount());
						user.setTrendsCount(profileUser.getTrendsCount());
						user.setAvatar(profileUser.getAvatar());
						AccountManager.saveUser(mContext, user);
					}
				}
				if (getActivity() != null) {
					BitmapBinder.bindCircularNetImage(mContext, mAvatarView, mUser.getAvatar(), R.drawable.default_avatar_round_small);
					mTrendsCountView.setText(String.valueOf(mUser.getTrendsCount()));
					mFansCountView.setText(String.valueOf(mUser.getFansCount()));
					mFollowCountView.setText(String.valueOf(mUser.getFollowCount()));
					mIntegralCountView.setText(String.valueOf(mUser.getIntegral()));
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}, params, OtherUserDataTO.class);
		RequestManager.startRequest(mContext, request);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edit: {
			Intent intent = new Intent(getActivity(), ProfileDetailActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.trends_layout: {
			long targetUid = mUser == null ? 0 : mUser.getUid();
			TrendsListActivity.start(getActivity(), mContext.getString(R.string.my_trends), targetUid);
		}
			break;
		case R.id.my_fishing_date: {
			Intent intent = new Intent(getActivity(), MyFishingActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.follow_layout: {
			Intent intent = new Intent(getActivity(), FriendsActivity.class);
			startActivity(intent);
			break;
		}
		case R.id.fans_layout: {
			Intent intent = new Intent(getActivity(), FriendsActivity.class);
			intent.putExtra(Constants.EXTRA_POSITION, 1);
			startActivity(intent);
			break;
		}
		case R.id.my_fav: {
			Intent intent = new Intent(getActivity(), MyFavoriteActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.feedback: {
			Intent intent = new Intent(getActivity(), FeedbackActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.about: {
			Intent intent = new Intent(getActivity(), WebViewActivity.class);
			intent.putExtra(Constants.EXTRA_URL, UriHelper.getAboutUrl());
			intent.putExtra(Constants.EXTRA_TITLE, getString(R.string.about_yuba));
			startActivity(intent);
		}
			break;
		case R.id.grade: {
			Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
			break;
		case R.id.more: {
			Intent intent = new Intent(getActivity(), SettingActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.avatar: {
			mEditAvatar = true;
			pickImage(true);
		}
			break;
		case R.id.cover: {
			mEditAvatar = false;
			pickImage(false);
		}
			break;
		case R.id.integral: {
			Intent intent = new Intent(getActivity(), IntegralListActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.contribution: {
			Intent intent = new Intent(getActivity(), ContributionActivity.class);
			startActivity(intent);
		}
			break;
		default:
			break;
		}
	}

	private void pickImage(boolean scale) {
		if (UiUtil.isFastDoubleClick()) {
			return;
		}
		if (mPopup != null && mPopup.isShowing())
			return;
		mPopup = new AvatarPickerPopup(getActivity(), scale);
		ViewGroup decor = (ViewGroup) getActivity().getWindow().getDecorView();
		mPopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == Constants.REQUEST_CODE_PICK_PHOTO || requestCode == Constants.REQUEST_CODE_TAKE_PHOTO) {
				String imagePath = data.getStringExtra("CropperPhotoPath");
				File imageFile = new File(imagePath);
				if (mEditAvatar) {
					updateAvatar(imageFile);
				} else {
					updateCover(imageFile);
				}
			}
		}
	}

	private void updateCover(final File coverFile) {
		if (mUser.isExpired()) {
			BitmapBinder.bindNetImage(mContext, mCoverView, mUser.getCover(), R.drawable.default_cover, false);
			Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
			LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
		} else {
			MultiPartRequest<UpdateCoverDataTO> request = RequestManager.getUpdateCoverRequest(new Listener<UpdateCoverDataTO>() {

				@Override
				public void onResponse(UpdateCoverDataTO response) {
					if (getActivity() != null) {
						mProgressDialog.dismiss();
						if (response == null) {
							Toast.makeText(mContext, R.string.update_failed, Toast.LENGTH_SHORT).show();
							BitmapBinder.bindNetImage(mContext, mCoverView, mUser.getCover(), R.drawable.default_cover, false);
						} else {
							if (response.isSuccess()) {
								String newCover = response.getCover();
								mUser.setCover(newCover);
								BitmapBinder.bindNetImage(mContext, mCoverView, newCover, R.drawable.default_cover, false);
								AccountManager.saveUser(mContext, mUser);
							} else {
								BitmapBinder.bindNetImage(mContext, mCoverView, mUser.getCover(), R.drawable.default_cover, false);
								if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
									Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
									LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
								} else {
									String msg = response.getMsg();
									msg = TextUtils.isEmpty(msg) ? getString(R.string.update_failed) : msg;
									Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
								}
							}
						}
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					if (getActivity() != null) {
						mProgressDialog.dismiss();
						Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
						BitmapBinder.bindNetImage(mContext, mCoverView, mUser.getCover(), R.drawable.default_cover, false);
					}
				}
			}, mUser, coverFile);
			mProgressDialog.show();
			RequestManager.startUpload(mContext, request);
		}
	}

	private void updateAvatar(final File avatarFile) {
		if (mUser.isExpired()) {
			BitmapBinder.bindCircularNetImage(mContext, mAvatarView, mUser.getAvatar(), R.drawable.default_avatar_round_small);
			Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
			LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
		} else {
			MultiPartRequest<UpdateAvatarDataTO> request = RequestManager.getUpdateAvatarRequest(new Listener<UpdateAvatarDataTO>() {

				@Override
				public void onResponse(UpdateAvatarDataTO response) {
					if (getActivity() != null) {
						mProgressDialog.dismiss();
						if (response == null) {
							Toast.makeText(mContext, R.string.update_failed, Toast.LENGTH_SHORT).show();
							BitmapBinder.bindCircularNetImage(mContext, mAvatarView, mUser.getAvatar(), R.drawable.default_image_small);
						} else {
							if (response.isSuccess()) {
								String newAvatar = response.getAvatar();
								mUser.setAvatar(newAvatar);
								BitmapBinder.bindCircularNetImage(mContext, mAvatarView, newAvatar, R.drawable.default_avatar_round_small);
								AccountManager.saveUser(mContext, mUser);
							} else {
								BitmapBinder.bindCircularNetImage(mContext, mAvatarView, mUser.getAvatar(), R.drawable.default_image_small);
								if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
									Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
									LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
								} else {
									String msg = response.getMsg();
									msg = TextUtils.isEmpty(msg) ? getString(R.string.update_failed) : msg;
									Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
								}
							}
						}
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					if (getActivity() != null) {
						mProgressDialog.dismiss();
						Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
						BitmapBinder.bindCircularNetImage(mContext, mAvatarView, mUser.getAvatar(), R.drawable.default_image_small);
					}
				}
			}, mUser, avatarFile);
			mProgressDialog.show();
			RequestManager.startUpload(mContext, request);
		}
	}

}
